import { STORAGE_KEYS } from '@vue-turbo-stack/shared';

// 移动端认证工具
export class AuthUtils {
  // 保存认证信息（token + 用户信息）
  static saveAuth(token: string, user: any) {
    if (typeof window !== 'undefined') {
      localStorage.setItem(STORAGE_KEYS.AUTH_TOKEN, token);
      localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(user));
      // 兼容旧逻辑：保留原有键，避免路由守卫受影响
      localStorage.setItem('manager_token', token);
      if (user?.fullName || user?.username) {
        localStorage.setItem('manager_name', user.fullName || user.username);
      }
    }
  }

  static getToken(): string | null {
    if (typeof window !== 'undefined') {
      return (
        localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN) ||
        localStorage.getItem('manager_token')
      );
    }
    return null;
  }

  static getUser<T = any>(): T | null {
    if (typeof window !== 'undefined') {
      const userStr = localStorage.getItem(STORAGE_KEYS.USER_INFO);
      if (userStr) {
        try { return JSON.parse(userStr) as T; } catch { return null; }
      }
    }
    return null;
  }

  static clearAuth() {
    if (typeof window !== 'undefined') {
      localStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
      localStorage.removeItem(STORAGE_KEYS.USER_INFO);
      localStorage.removeItem('manager_token');
      localStorage.removeItem('manager_name');
    }
  }

  static isAuthenticated(): boolean {
    return !!this.getToken();
  }
}

